package com.xdf.xzymanagementsystem.util;

import com.sun.org.apache.xerces.internal.parsers.SAXParser;
import com.sun.org.apache.xerces.internal.parsers.XMLParser;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackageAccess;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.model.SharedStringsTable;
import org.xml.sax.*;

import java.io.*;
import java.util.Iterator;

/**
 * @program: xzy-management-system
 * @description: Excel解析类
 * @author: 张柯
 * @create: 2021-03-19 11:12
 **/
public class ExcelParserUtils {
    /**
     * 读取Excel
     *
     * @param file
     */
    public void process(File file) {
        OPCPackage opcPackage = null;
        SharedStringsTable sharedStringsTable = null;
        try {
            opcPackage = OPCPackage.open(file, PackageAccess.READ);
            XSSFReader reader = new XSSFReader(opcPackage);
            sharedStringsTable = reader.getSharedStringsTable();
            XMLReader parser = new SAXParser();
            Iterator<InputStream> it = reader.getSheetsData();
            while (it.hasNext()) {
                try (InputStream inputStream = it.next()) {
                    InputSource inputSource = new InputSource(inputStream);
                    inputSource.setEncoding("UTF-8");
                    byte[] b = new byte[1024];
                    StringBuilder sb = new StringBuilder();
                    int aa;
                    while ((aa = inputStream.read(b)) != -1) {
                        sb.append(aa);
                    }
                    System.out.println(sb.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            System.out.println(sharedStringsTable.getCount());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (opcPackage != null) {
                try {
                    opcPackage.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (sharedStringsTable != null) {
                try {
                    sharedStringsTable.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        File file = new File("C:\\Users\\zp-pc\\Desktop\\成品与半成品(1).xlsx");
        ExcelParserUtils utils = new ExcelParserUtils();
        if (file.exists()) {
            try {
                FileInputStream fis = new FileInputStream(file);

                utils.process(file);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
